var AgentProviderForm = function () {
  var ProviderFormModel = function (provider, type) {
    BaseModel.call(this);

    var self = this;
    var fn = {
      initData: function (provider, type) {
        if (type === 'add') {
          this.initProvider();
          return;
        }
        this.setProvider(provider);
      },

      initProvider: function () {
        var provider = {
          paymentWay: 1,
          status: '使用',
          isTax: 0,
          preight: 1
        };

        var fields = ['id', 'customerName', 'customerCode', 'contact', 'phone', 'paymentWay', 'status', 'isTax', 'preight',
          'fax', 'address'
        ];
        self.setDataFromObj(provider, fields, '');
        self.parentSupplier = '';
        self.email = [];
      },

      setProvider: function (provider) {
        var fields = ['id', 'customerName', 'customerCode', 'contact', 'phone', 'paymentWay', 'status', 'isTax', 'preight',
          'fax', 'address'
        ];
        self.setDataFromObj(provider, fields, '');

        var parentId = provider.parentId;
        var parentName = provider.parentName;
        var parentSupplier = {
          id: String(parentId),
          name: parentName
        };
        self.parentSupplier = parentSupplier;

        var email = provider.email;
        if (email) {
          email = email.join('\n');
        } else {
          email = '';
        }
        self.email = email;
      }
    };

    this.checkValid = function () {
      var requiredFields = ['customerCode', 'customerName', 'parentSupplier', 'contact', 'paymentWay', 'status'];
      return CheckVaildUtil.checkNullField(requiredFields, this);
    };

    this.checkEmailValid = function (email, emailReg) {
      if (email === '') {
        return true;
      }

      var emails = email.split(';');
      for (var i = 0; i < emails.length; i++) {
        var data = emails[i];
        if (!emailReg.test(data)) {
          return false;
        }
      }
      return true;
    };

    this.getObject = function () {
      var postData = {
        type: 1
      };
      var id = this.id;
      if (id !== '') {
        postData.id = id;
      }

      var parentSupplier = this.parentSupplier;
      if (parentSupplier !== '') {
        postData.parentId = parentSupplier.id;
        postData.parentName = parentSupplier.name;
      }

      var fields = ['customerName', 'customerCode', 'contact', 'phone', 'paymentWay', 'status', 'isTax', 'preight',
        'fax', 'address'
      ];
      this.setPostData(postData, fields, true, true);

      var email = self.email.trim();
      if (email !== '') {
        email = email.split(/[(\r\n)\r\n;]+/g);
        email = _.uniq(email);
        var newEmail = [];
        for (var i = 0; i < email.length; i++) {
          var value = email[i].trim();
          if (value !== '') {
            newEmail.push(value);
          }
        }
        email = newEmail.join(';');
      }
      postData.email = email;
      return postData;
    };

    fn.initData(provider, type);
  };

  var template = /* html */ `
    <div class="agent-provider-form" v-loading.fullscreen.lock="loading">
      <el-form label-width="auto" size="medium">
        <el-form-item :required="type==='add'" label="代理商代码">
          <el-input v-if="type==='add'" class="form-input" v-model="providerForm.customerCode"></el-input>
          <span v-else>{{providerForm.customerCode}}</span>
        </el-form-item>
        <el-form-item :required="type==='add'" label="代理商名称">
          <el-input v-if="type==='add'" class="form-input" v-model="providerForm.customerName"></el-input>
          <span v-else>{{providerForm.customerName}}</span>
        </el-form-item>
        <el-form-item required label="供应商">
          <el-select filterable class="form-input" v-model="providerForm.parentSupplier" value-key="id">
            <el-option v-for="supplier in supplierList" :key="supplier.id" :value="supplier" :label="supplier.name">
            </el-option>
          </el-select>
          <div style="color:#ff0000;line-height:25px">请选择该代理商代理哪个供应商的物料</div>
        </el-form-item>
        <el-form-item required label="联系人">
          <el-input class="form-input" v-model="providerForm.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input class="form-input" v-model="providerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
        <el-input class="form-input" v-model="providerForm.email" type="textarea" :autosize="autosizeOption" resize="none" placeholder="多个邮箱换行或者;隔开"></el-input>
        </el-form-item>
        <el-form-item required label="付款结算方式">
          <el-select class="form-input"  v-model="providerForm.paymentWay">
            <el-option v-for="paymentWay in paymentWayList" :key="paymentWay.value" :value="paymentWay.value" :label="paymentWay.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="状态">
          <el-select class="form-input" v-model="providerForm.status">
            <el-option label="使用" value="使用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否含税">
          <el-select class="form-input" v-model="providerForm.isTax">
            <el-option label="含税" :value="0"></el-option>
            <el-option label="不含税" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运费负担">
          <el-select class="form-input" v-model="providerForm.preight">
            <el-option label="我司" :value="0"></el-option>
            <el-option label="供方" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="传真">
          <el-input class="form-input" v-model="providerForm.fax"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input class="form-input" v-model="providerForm.address"></el-input>
        </el-form-item>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="ensure">
          <span v-if="type==='add'">新增</span>
          <span v-else>修改</span>
        </el-button>
      </div>
    </div>
  `;

  return {
    props: {
      provider: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      dropdownOption: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    data: function () {
      return {
        loading: false,
        providerForm: new ProviderFormModel(this.provider, this.type),
        paymentWayList: i18n.getDropDown('customer.paymentWayType', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 18, 24]),
        supplierList: [],
        emailReg: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
        autosizeOption: {
          minRows: 2,
          maxRows: 8
        }
      };
    },

    created: function () {
      this.setSupplierList();
    },

    methods: {
      setSupplierList: function () {
        var dropdownOption = this.dropdownOption;
        var supplierList = dropdownOption.supplierList;
        if (supplierList !== undefined) {
          this.supplierList = supplierList;
          return;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('basicData/queryCustomersTow', {
          type: 1,
          status: '使用'
        }, false).then(function (res) {
          var supplierList = res.returnData;
          supplierList = _.map(supplierList, function (supplier) {
            return {
              id: supplier.id,
              name: supplier.customerName
            };
          });
          self.supplierList = supplierList;
          dropdownOption.supplierList = supplierList;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      ensure: function () {
        var providerForm = this.providerForm;
        var code = providerForm.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`customer.error.agent.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        var postData = providerForm.getObject();
        var emailVaild = providerForm.checkEmailValid(postData.email, this.emailReg);
        if (!emailVaild) {
          this.$alert("请输入有效email", "信息");
          return;
        }

        if (this.type === 'add') {
          this.addProvider(postData);
        } else {
          this.updateProvider(postData);
        }
      },

      addProvider: function (postData) {
        this.loading = true;
        var self = this;
        ajaxRequest('basicData/insertCustomerSub', postData).then(function () {
          self.loading = false;
          self.$alert('代理商新增成功', '信息', {
            callback: function () {
              self.$emit('save-success', self.type);
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      updateProvider: function (postData) {
        this.loading = true;
        var self = this;
        ajaxRequest('basicData/updateCustomerSub', postData).then(function () {
          self.loading = false;
          self.$alert('代理商修改成功', '信息', {
            callback: function () {
              self.$emit('save-success', self.type);
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    template: template
  };
}();
